package everyday;

import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

/**
 * 利率计算相关
 *
 * @author gaojie
 * @date 2024-04-25
 */
public class RateOperation {

    /**
     * 计算提前还款能够减少金额
     */
    @Test
    void test() {
        final BigDecimal rate = new BigDecimal("0.045");
        String rateStr = rate.multiply(new BigDecimal("100")) + "%";
        System.out.println("当前房贷利率：" + rateStr);

        final BigDecimal amount = new BigDecimal("50000");
        System.out.println("提前还款金额：" + amount);

        final LocalDate loanStart = LocalDate.parse("2020-08-08");
        System.out.println("贷款开始日期：" + loanStart);

        System.out.println("----------------------------------------------------");

        final long payedMonth = loanStart.until(LocalDate.now(), ChronoUnit.MONTHS);
        System.out.println("贷款已还月数：" + payedMonth);

        final BigDecimal unPayedMonth = BigDecimal.valueOf(360 - payedMonth);
        System.out.printf("贷款剩余月数：%s=[总月数-已还月数]=(360-%s)%n", unPayedMonth, payedMonth);

        final BigDecimal yearInterest = amount.multiply(rate);
        System.out.printf("每年减少利息：%s=[提前还款金额*年利率]=(%s*%s)%n", yearInterest, amount, rateStr);

        final BigDecimal monthInterest = yearInterest.divide(new BigDecimal(12), 2, RoundingMode.HALF_UP);
        System.err.printf("每月减少利息：%s=[每年减少利息/月数]=(%s/%s)%n", monthInterest, yearInterest, 12);

        final BigDecimal totalInterest = monthInterest.multiply(unPayedMonth);
        System.err.printf("总共减少利息：%s=[每月减少利息*贷款剩余月数]=(%s*%s)%n", totalInterest, monthInterest, unPayedMonth);

        final BigDecimal monthPrincipal = amount.divide(unPayedMonth, 2, RoundingMode.HALF_UP);
        System.out.printf("每月减少本金：%s=[提前还款金额/贷款剩余月数]=(%s/%s)%n", monthPrincipal, amount, unPayedMonth);

        final BigDecimal monthAmount = monthPrincipal.add(monthInterest);
        System.err.printf("每月减少金额：%s=[每月减少本金+每月减少利息]=(%s+%s)%n", monthAmount, monthPrincipal, monthInterest);

        final BigDecimal totalAmount = totalInterest.add(amount);
        System.out.printf("总共减少金额：%s=[每月减少本金+提前还款金额]=(%s+%s)%n", totalAmount, totalInterest, amount);
    }
}
